package net.asfun.jvalog.vo;

import java.util.ArrayList;
import java.util.List;

import net.asfun.jvalog.common.InteractException;
import net.asfun.jvalog.common.JdoerFactory;
import net.asfun.jvalog.entity.Label;
import net.asfun.jvalog.entity.Relation;
import net.asfun.jvalog.resource.MeterDao;
import net.asfun.jvalog.util.Bridge;

public class Tag{

	private Label label;
	
	private List<Relation> pos;
	
	public Tag(Label label) {
		if ( label == null ) {
			throw new InteractException("Tag not found");
		}
		this.label = label;
	}

	private void setPosts() {
		if ( null == pos ) {
			pos = Bridge.getRelationsByRight(label.getKey(), Bridge.POST_TAG);
		}
	}
	
	public int getPostCount() {
		return MeterDao.getCount(label.getKey());
	}
	
	protected static Tag load(Long id) {
		return new Tag(JdoerFactory.jdoLabel.load(id));
	}
	
	public String getName() {
		return label.getName();
	}
	
	public String getSlogan() {
		return label.getSlogan();
	}
	
	public Long getId() {
		return label.getKey().getId();
	}

	public String getLink() {
		return Site.getInstance().getUrl() + "tag/" + label.getSlogan();
	}
	
	public List<Post> listPublishedPosts(Pager pager) {
		setPosts();
		pager.setTotal(getPostCount());
		List<Post> list = new ArrayList<Post>();
		int j=0;
		for(int i=pos.size(); i>0; ) {
			Post post = Post.load(pos.get(--i).getLeft().getId());
			if ( post != null && post.isPublished() ) {
				//paging
				if ( j >= pager.getStart() && 
						j < pager.getEnd() ) {
					list.add(post);
				}
				j++;
			}
		}
		if ( list.isEmpty() && pager.getIndex() > 1 ) {
			throw new InteractException("Tag pager no record");
		}
		return list;
	}
}
